package com.nl.controller.web.service;

import java.io.IOException;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.DocumentException;
import org.jdom.CDATA;
import org.jdom.Comment;
import org.jdom.DocType;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.EntityRef;
import org.jdom.JDOMException;
import org.jdom.ProcessingInstruction;
import org.jdom.Text;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nl.controller.common.util.AES;
import com.nl.controller.common.util.HttpClientUtil;
import com.nl.controller.web.bean.XzMsisdn;
import com.nl.controller.web.mapper.SmsInterfaceMapper;
import com.nl.controller.web.util.GZipUtil;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SmsInterfaceService {
	@Autowired
	private SmsInterfaceMapper smsInterfaceMapper;
	private String url = "http://172.18.42.19:8991/safeporxy/gbs_http_xj";




	public void  xzTransferMsisdn(){
		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>   ");
		sBuffer.append("<InterBOSS>   ");
		sBuffer.append("  <OrigDomain>BOSS</OrigDomain>    ");
		sBuffer.append("  <HomeDomain>LBMP</HomeDomain>    ");
		sBuffer.append("  <BIPCode>BIP4B249</BIPCode>    ");
		sBuffer.append("  <BIPVer>0100</BIPVer>    ");
		sBuffer.append("  <ActivityCode>T2101708</ActivityCode>    ");
		sBuffer.append("  <ActionCode>0</ActionCode>    ");
		sBuffer.append("  <Routing>   ");
		sBuffer.append("    <RouteType>00</RouteType>    ");
		sBuffer.append("    <RouteValue>000</RouteValue>   ");
		sBuffer.append("  </Routing>    ");
		sBuffer.append("  <ProcID>5202</ProcID>    ");
		sBuffer.append("  <TransIDO>SU5202</TransIDO>    ");
		sBuffer.append("  <ProcessTime>%S</ProcessTime>   "); 
		sBuffer.append("  <TestFlag>0</TestFlag>    ");
		sBuffer.append("  <MsgSender>0000</MsgSender>    ");
		sBuffer.append("  <MsgReceiver>0050</MsgReceiver>    ");
		sBuffer.append("  <SvcContVer>0100</SvcContVer>   "); 
		sBuffer.append("  <SvcCont><![CDATA[<?xml version=\"1.0\" encoding=\"UTF-8\"?>  ");
		sBuffer.append("<LMemInfo>  ");
		sBuffer.append("<PkgSeq>20190815163812</PkgSeq>  ");
		sBuffer.append("<UserInfo>  ");
		sBuffer.append("<OrdID>62505160001</OrdID>  ");
		SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMddHHmmss");
		int uu = (int)(Math.random()*900 + 100);
		String myStr = Integer.toString(uu);
		String OprSeq = sdf3.format(new Date())+myStr;//流水号
		sBuffer.append("<OprSeq>"+OprSeq+"</OprSeq> ");
		sBuffer.append("<ECID>51603486272</ECID>  ");
		String result="" ;
		List<XzMsisdn> list = findMsisdn();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
		if (list.size() >0) {
			for (XzMsisdn xzMsisdn : list) {
				String msisdn = xzMsisdn.getReceiver();
				if (msisdn.length()==22) {
					msisdn = AES.decrypt(msisdn, "HuaDongJieSuo123");
				}
				sBuffer.append("<UserData><MSISDN>"+msisdn+"</MSISDN><OprCode>01</OprCode><EfftT>"+sdf.format(new Date())+"</EfftT><PayECID>1633022018230764</PayECID><LocType>A</LocType><UEType>1</UEType></UserData>  ");
			}
			sBuffer.append("</UserInfo>  ");
			sBuffer.append("</LMemInfo>]]> </SvcCont>   ");
			sBuffer.append("</InterBOSS>  ");
			String rxml = sBuffer.toString();
			rxml = String.format(rxml, sdf1.format(new Date()));
			//log.info(rxml);
			rxml = GZipUtil.gzip(rxml);
			HttpClientUtil httpClientUtil = new HttpClientUtil();
			Map<String,String> map = httpClientUtil.httpPostWithXml(url, rxml, "utf-8", "utf-8", null);
			String flag = map.get("retCode");
			String retMsg = map.get("retMsg");
			//log.info("code"+flag+";msg"+retMsg);
//			String flag = "0";
			String cdata="";
//			String retMsg = "<?xml version=\"1.0\"?>"+
//							"<InterBOSS>"+
//							"  <OrigDomain>BOSS</OrigDomain>"+
//							"  <HomeDomain>LBMP</HomeDomain>"+
//							"  <BIPCode>BIP4B249</BIPCode>"+
//							"  <BIPVer>0100</BIPVer>"+
//							"  <ActivityCode>T2101708</ActivityCode>"+
//							"  <ActionCode>1</ActionCode>"+
//							"  <Routing>"+
//							"    <RouteType>00</RouteType>"+
//							"    <RouteValue>000</RouteValue>"+
//							"  </Routing>"+
//							"  <ProcID>5202</ProcID>"+
//							"  <TransIDO>SU5202</TransIDO>"+
//							"  <ProcessTime>20190816153252</ProcessTime>"+
//							" <Response>"+
//							"   <RspType>0</RspType>"+
//							"    <RspCode>0000</RspCode>"+
//							"    <RspDesc/>"+
//							"  </Response>"+
//							"  <TestFlag>0</TestFlag>"+
//							"  <MsgSender>0000</MsgSender>"+
//							"  <MsgReceiver>0050</MsgReceiver>"+
//							"  <SvcContVer>0100</SvcContVer>"+
//							"  <SvcCont><![CDATA[<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
//							"<BizInfoRsp>"+
//							"  <OprTime>20190816153222</OprTime>"+
//							"  <ECID>9919156753</ECID>"+
//							"  <OrdID>59919156753</OrdID>"+
//							"  <OprSeq>9119080149340263</OprSeq>"+
//							"  <Rslt>"+
//							"    <MobNum>13022515378</MobNum>"+
//							"    <RspCode>00</RspCode>"+
//							"    <RspDesc>success</RspDesc>"+
//							"  </Rslt>"+
//							"  <Rslt>"+
//							"    <MobNum>15150570249</MobNum>"+
//							"    <RspCode>00</RspCode>"+
//							"   <RspDesc>success</RspDesc>"+
//							"  </Rslt>"+
//							"  <RspCode>00</RspCode>"+
//							"</BizInfoRsp>]]></SvcCont>"+
//							"</InterBOSS>";
			if("0".equals(flag)){
				result="调用成功";
//				retMsg = GZipUtil.gzip(retMsg);
				log.info("徐州接口"+result+";解压前返回报文:"+retMsg);
				retMsg = GZipUtil.gunzip(retMsg);
				log.info("徐州接口"+result+";解压后返回报文:"+retMsg);
				cdata= cdata(retMsg);
				if (null != cdata && !"".equals(cdata)) {
					List<String> msisdnList = parseXml(cdata);
					List<XzMsisdn> sXzMsisdns = new ArrayList<XzMsisdn>();
					for (String string : msisdnList) {
						for (XzMsisdn xzMsisdn : list) {
							String msisdn = xzMsisdn.getReceiver();
							if (msisdn.equals(string)) {
								sXzMsisdns.add(xzMsisdn);
								continue;
							}
						}
					}
					updateMsisdn(sXzMsisdns);

				}
			}else if("-1".equals(flag)){
				result="调用失败";
				log.error("徐州接口"+result+";返回报文:"+retMsg);
			}
			log.info(result);
		}else {
			log.info( "暂无号码发送");
		}

	}
	public List<XzMsisdn> findMsisdn(){
		List<XzMsisdn> list = new ArrayList<XzMsisdn>();
		list = smsInterfaceMapper.findMsisdn();
		return list;
	}
	public void updateMsisdn(List<XzMsisdn> xzMsisdns){
		try {
			Integer updateMsidn =-1;
			for (XzMsisdn xzMsisdn : xzMsisdns) {
				log.info(xzMsisdn.toString());
				updateMsidn = smsInterfaceMapper.updateMsidn(xzMsisdn.getReceiver(),xzMsisdn.getId());
			}
			if (updateMsidn ==1) {
				log.info("更新徐州号码表成功");
			}else {
				log.error("更新徐州号码表失败");
			}
		} catch (Exception e) {
			log.error(e.toString());
			e.printStackTrace();
		}
	}

	private String cdata(String xml){
		SAXBuilder builder = new SAXBuilder(); 
		try { 
			Document document = builder.build(new StringReader(xml)); 
			Element root = document.getRootElement(); 
			Element data = root.getChild("SvcCont"); 
			List content = data.getContent(); 
			String result = "";
			for (Object o : content) { 
				if (o instanceof Comment) { 
					Comment comment = (Comment) o; 
					System.out.println("Comment   = " + comment); 
				} else if (o instanceof Element) { 
					Element element = (Element) o; 
					System.out.println("Element   = " + element); 
				} else if (o instanceof CDATA) { 
					CDATA cdata = (CDATA) o;
					result = cdata.getText();
					xml = result;
				} else if (o instanceof DocType) { 
					DocType docType = (DocType) o; 
					System.out.println("DocType   = " + docType); 
				} else if (o instanceof ProcessingInstruction) { 
					ProcessingInstruction pi = (ProcessingInstruction) o; 
					System.out.println("PI        = " + pi); 
				} else if (o instanceof EntityRef) { 
					EntityRef entityRef = (EntityRef) o; 
					System.out.println("EntityRef = " + entityRef); 
				} else if (o instanceof Text) { 
					Text text = (Text) o; 
					System.out.println("Text      = " + text); 
				} 
			} 
		} catch (JDOMException e) { 
			e.printStackTrace(); 
		} catch (IOException e) { 
			e.printStackTrace(); 
		}
		return xml; 
	}

	private List<String> parseXml(String xml){
		List<String> msisdnList = new ArrayList<String>();
		try {
			org.dom4j.Document doc = org.dom4j.DocumentHelper.parseText(xml);
			org.dom4j.Element root = doc.getRootElement();
			System.out.println("Document类getRootElement()=" + root.getName());
			//			Element Rslt = (Element) doc.selectSingleNode("/BizInfoRsp");
			List attrList = null;
			if (root != null) {
				// 有重复格式的数据，用此种方式，返回一个List 注意括号中元素的写法
				attrList = root.elements("Rslt");
			}
			if (attrList != null) {
				Iterator iterator = attrList.iterator();
				while (iterator.hasNext()) {// 循环List中的元素
					org.dom4j.Element attrEle = (org.dom4j.Element) iterator.next();
					org.dom4j.Element attrCode = (org.dom4j.Element) attrEle.selectSingleNode("MobNum");
					String msisdn = attrCode.getTextTrim();
					org.dom4j.Element attValue = (org.dom4j.Element) attrEle.selectSingleNode("RspCode");
					// 根据实际操作操作数据库
					String respCode = attValue.getTextTrim();
					if ("00".equals(respCode)) {
						try {
							msisdn = AES.encrypt(msisdn, "HuaDongJieSuo123");
							msisdnList.add(msisdn);
						} catch (Exception e) {
							log.error(e.toString());
							e.printStackTrace();
						}
					}
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return msisdnList;
	}

}
